package com.example.lots_of_demo.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.lots_of_demo.bo.PermissionResBo;
import com.example.lots_of_demo.bo.ResBo;
import com.example.lots_of_demo.model.Permission;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface PermissionDao extends BaseMapper<Permission> {

    /**
     * 根据权限编码分组 查询所有可用权限下的所有可用资源
     * @return List<PermissionResBo>
     */
    @Select("SELECT P.`CODE` FROM PERMISSION P")
    @Results({
            @Result(column = "code", property = "code"),
            @Result(column = "code", property = "res", many = @Many(select = "com.example.lots_of_demo.dao.PermissionDao.getResByPermissionCode"))
    })
    List<PermissionResBo> getResGroupByPermissionCode();

    /**
     * 根据权限编码 获取该权限下所有资源
     * @param code 权限编码
     * @return List<ResBo>
     */
    @Select("SELECT R.ID AS RES_ID, P.ID AS PERMISSION_ID , R.`DESC` FROM RES R LEFT JOIN R_PERMISSION_RES RPR ON R.ID = RPR.RES_ID LEFT JOIN PERMISSION P ON RPR.PERMISSION_ID = P.ID WHERE P.`CODE` != #{code} AND R.ID " +
            "IN " +
            "( " +
            "SELECT R.ID FROM RES R LEFT JOIN R_PERMISSION_RES RPR ON R.ID = RPR.RES_ID LEFT JOIN PERMISSION P ON RPR.PERMISSION_ID = P.ID WHERE P.`CODE` = #{code} " +
            ") ")
    @ResultType(ResBo.class)
    List<ResBo> getResByPermissionCode(String code);

    /**
     * 根据 子权限ID 查找 父权限组 绑定的权限
     * @param permissionId 子权限ID
     * @return Permission
     */
    @Select("SELECT * FROM permission P WHERE ID = " +
            "( " +
            "SELECT permission_id FROM r_permission_res RPR WHERE RES_ID = " +
            "( " +
            "SELECT RPR.RES_ID FROM PERMISSION P LEFT JOIN r_permission_res RPR ON P.ID = RPR.permission_id WHERE P.ID = #{permissionId} " +
            ") " +
            "AND permission_id != #{permissionId}) ")
    @ResultType(Permission.class)
    Permission selectParentPermissionBySubPermissionId(Long permissionId);
}